<!DOCTYPE html>
<html lang="zh">
  <head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>模型加载</title>
  </head>
  <body>
    <script type="module">
      // 引入three.js
      import * as THREE from "three";
      import { GLTFLoader } from "three/examples/jsm/loaders/GLTFLoader.js";
      import { scene, camera, controls } from "/src/utils/init.js";

      function initBase() {
        camera.position.set(3, 2, -2); //统一设置
        // 实例化加载器并加载模型
        new GLTFLoader().load("/src/model/gumball_car.glb", (gltf) => {
          // 取出模型对象并添加到场景中
          const model = gltf.scene;
          // 遍历物理内部每个小物体
          model.traverse((obj) => {
            // console.log(obj);
            if (obj.name == "Object_13") {
              //修改车身材质
              //   obj.material.color = new THREE.Color(0xff0000);
            }
          });
          scene.add(model);
        });
      }

      // 光源
      function createLight() {
        // 环境光 只能照亮物体，不能反光
        const light = new THREE.AmbientLight(0xffffff, 1);
        scene.add(light);

        // 平行光
        const directionLight = new THREE.DirectionalLight(0xffffff, 2);
        directionLight.position.set(3, 3, 3);
        scene.add(directionLight);

        // 平行光辅助对象
        const helper = new THREE.DirectionalLightHelper(directionLight, 1);
        scene.add(helper);
      }

      initBase();
      createLight();

      // 监听轨道控制器-旋转/拖拽等事件
      controls.addEventListener("change", () => {
        // console.log(camera.position); // 摄像机位置
        // console.log(controls.target); // 正在观察的坐标点对象
      });

      //双击事件
      window.addEventListener("dblclick", () => {
        camera.position.set(0.28, 0.92, 0.36); // 设置相机位置
        controls.target = new THREE.Vector3(0.25, 0.71, 0.75); // 设置观察点（摄像机朝向点位）
      });
    </script>
  </body>
</html>
